package cn.stylefeng.guns.modular.rest.transport;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.stylefeng.guns.core.util.MapUtils;
import cn.stylefeng.guns.modular.rest.aop.UserAop;
import cn.stylefeng.guns.modular.rest.transport.vo.StoreInfo;
import cn.stylefeng.guns.modular.transport.model.params.InwarehouseTrackParam;
import cn.stylefeng.guns.modular.transport.service.InwarehouseTrackService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Comparator;

@Controller
@RequestMapping("/rest/inwarehouseTrack")
public class RestInwarehouseTrackController {

    @Autowired
    private UserAop userAop;

    @Value("${map.key}")
    private String amapKey;
    @Value("${map.url}")
    private String amapUrl;




    @Autowired
    private InwarehouseTrackService inwarehouseTrackService;

    @RequestMapping("/uploadPoint")
    @ResponseBody
    public ResponseData getDriverEvalList(@RequestBody InwarehouseTrackParam inwarehouseTrackParam) {
        User user = userAop.getUser();
        inwarehouseTrackParam.setSiji(user.getAccount());

        Long clientVolSumId = inwarehouseTrackParam.getClientVolSumId();

        //根据的部门id获取仓库信息

        StoreInfo storeInfo = inwarehouseTrackService.getStoreInfoByClientVolSumId(clientVolSumId);
        String latitude = storeInfo.getLatitude();
        String longitude = storeInfo.getLongitude();


        String currentLatitude = inwarehouseTrackParam.getLatitude();
        String currentLongitude = inwarehouseTrackParam.getLongitude();

        String result = HttpUtil.get(amapUrl+"?origin="+currentLongitude+","+ currentLatitude+"&destination="+longitude +","+latitude+"&key="+amapKey);
        System.out.println(result);

        JSONObject jsonpoint = new JSONObject(result);
        if(jsonpoint.get("status").equals("1")){
            JSONObject route = (JSONObject)jsonpoint.get("route");
            JSONObject paths = route.getJSONArray("paths").getJSONObject(0);
            Object distance = paths.get("distance");
            Object duration = paths.get("duration");
            int durationM = Integer.valueOf(duration.toString()) / 60;
            inwarehouseTrackParam.setRemainKilometer(distance.toString());
            inwarehouseTrackParam.setRemainTime(durationM+"");
            inwarehouseTrackService.uploadPoint(inwarehouseTrackParam);
            return ResponseData.success(inwarehouseTrackParam);
        }else {
            return ResponseData.error("查询路径距离、时间失败，获取路径失败");
        }
    }
}
